'use client';

import { useAccount, useConnect, useDisconnect } from 'wagmi';
import { injected } from 'wagmi/connectors';
import { useEffect, useState } from 'react';

export function WalletConnectButton() {
  const { address, isConnected } = useAccount();
  const { disconnect } = useDisconnect();
  const { connectAsync, connectors, status } = useConnect();

  const [mounted, setMounted] = useState(false);
    const [connecting, setConnecting] = useState(false);
    const [errorMsg, setErrorMsg] = useState<string | null>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  // 防止 SSR 与 CSR 渲染不一致，直到组件挂载
  if (!mounted) return null;

  const handleConnect = async () => {
    if (connecting) return; // 防止重复点击
    setConnecting(true);

    const connector = connectors.find(c => c.id === 'injected');
    if (!connector) return;
    try {
      await connectAsync({ connector });
    } catch (err) {
      //console.error('Connection failed:', err);
      const message = err?.message || 'Unknown error';
      if (message.includes('already pending')) {
        setErrorMsg('请完成或取消前一个钱包连接请求后再尝试');
      } else {
        setErrorMsg(message);
      }
    } finally {
      setConnecting(false);
    }
    
  };

  if (isConnected) {
    return (
      <button
        onClick={() => disconnect()}
        className="bg-red-500 hover:bg-red-700 text-white font-semibold py-2 px-4 rounded-lg max-w-xs mx-auto block"
      >
        Disconnect ({address?.slice(0, 6)}...)
      </button>
    );
  }

  return (
    <button
      onClick={handleConnect}
      className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-lg max-w-xs mx-auto block"
    >
      Connect Wallet
    </button>
  );
}
